<template>
  <el-button @click="sendcode" :disabled="codeStatus" class="vcode_buttom" :style ="'height:'+ height +';width:'+width" type="danger">{{ codeText }}</el-button>
</template>

<script>
import {sendRegisterCode} from "@/api/user"
import { validatePhone } from "@/utils/validate";
export default {
  name: "VeCode",
  props: {
    verifyCode:{type: String, default: ""},
    phone: { type: String, default: "" },
    height: { type: String, default:"42px"},
    width: { type: String, default:"100%"},
    types: { type: Number,  default:0},
  },
  data() {
    return {
      mobile:this.phone,
      codeText: "发送验证码",
      codeTime: 120,
      codeStatus: false,
      formStatus: false,
      intvalTime: null
    };
  },
  watch: {
    phone(val,oval) {
      this.mobile = val;
    }
  },
  mounted() {
    clearInterval(this.intvalTime);
  },
  methods: {
    sendcode: async function() {
      clearInterval(this.intvalTime);
      if (!validatePhone(this.mobile)) {
        this.$message({
          type: "error",
          message: "手机号码不正确！"
        });
        return false;
      }

      if(!this.verifyCode) {
        this.$message({
          type: "error",
          message: "请输入图片验证码！"
        });
        return false;
      }
      if (this.codeStatus == true) {
        return false;
      }
      this.codeStatus = true;

      try {
        var res;
        if(this.types === 0){
          res = await sendRegisterCode({phone:this.mobile,verifyCode:this.verifyCode});
        }

        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "手机验证发送成功"
          });
          console.log(res);
          var that = this;
          that.intvalTime = setInterval(function() {
            that.codeTime -= 1;
            that.codeText = "剩余" + that.codeTime + "秒";
            if (that.codeTime < 1) {
              that.codeText = "发送验证码";
              that.codeStatus = false;
              clearInterval(that.intvalTime);
            }
          }, 1000);
        } else {
          this.codeStatus = false;
        }
      } catch (err) {
        console.log(err);
      }
    }
  }
};
</script>

<style>
.vcode_buttom{
  background-color: #ec7259;
  border: 1px solid #ec7259;
}
</style>
